package com.xing.oauth.server.aligenieController.vo;

import com.xing.oauth.common.response.ResultCode;
import com.xing.oauth.server.model.TokenDto;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletResponse;

public class OAuthResponseVo {

    public static ResponseEntity getErrorResponse(ResultCode resultCode) {
        OAuthResponse oAuthResponse = null;

        try {
            oAuthResponse = OAuthASResponse
                    .errorResponse(HttpServletResponse.SC_OK)
                    //                .setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT)
                    //                .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
                    //                .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
                    .setError(String.valueOf(resultCode.code()))
                    .setErrorDescription(resultCode.message())
                    .buildJSONMessage();
        } catch (OAuthSystemException e) {
            e.printStackTrace();
        }
        return new ResponseEntity(
                oAuthResponse.getBody(), HttpStatus.valueOf(oAuthResponse.getResponseStatus()));

    }

    /**
     * oAuth2.0正确返回
     *
     * @param tokenDto
     * @return
     */
    public static ResponseEntity getTokenResponse(TokenDto tokenDto) {

        //生成OAuth响应
        OAuthResponse response = null;
        try {
            OAuthASResponse
                    .tokenResponse(HttpServletResponse.SC_OK)
                    .setAccessToken(tokenDto.getAccessToken())
                    .setRefreshToken(tokenDto.getRefreshToken())
                    .setExpiresIn(String.valueOf(tokenDto.getAtExpiresIn()))
                    .buildJSONMessage();
        } catch (OAuthSystemException e) {
            e.printStackTrace();
        }
        //根据OAuthResponse生成ResponseEntity
        return new ResponseEntity(
                response.getBody(),
                HttpStatus.valueOf(response.getResponseStatus()));
    }

}
